package com.dzm.service.impl;

import com.dzm.constants.ClientConstant;
import com.dzm.constants.RedisConstant;
import com.dzm.service.TokenService;
import com.dzm.to.LoginUser;
import com.dzm.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 作者：Dzm
 * 时间：2024-08-31-13:04
 * 功能：
 */

@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Map<String, Object> getToken(LoginUser loginUser) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        loginUser.setUserId(uuid);
        Map<String, Object> map = new HashMap<>();
        map.put("userId", loginUser.getUser().getId());
        map.put("username", loginUser.getUser().getUsername());
        map.put("user_key", uuid);

        String token = JwtUtil.createToken(map);

        redisTemplate.opsForValue().set(RedisConstant.LOGIN_TOKEN + uuid, loginUser, 1, TimeUnit.DAYS);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);

        return resultMap;
    }

    @Override
    public Map<String, Object> getUserInfo(String tokenStr) {
        String token = tokenStr.replaceFirst(ClientConstant.CLIENT_TOKEN_PRE, "");
        Map<String, Object> claims = JwtUtil.parseToken(token);
        String username = (String) claims.get("username");

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("name", username);
        resultMap.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");

        return resultMap;
    }
}
